/*
 * Copyright madding.me.
 */
package com.madding.shared.net.wget;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.madding.shared.lang.StringUtil;

/**
 * 类Wget.java的实现描述：
 * 
 * @author madding.lip May 8, 2012 2:32:29 PM
 */
public class Wget {

    private final static Logger logger         = LoggerFactory.getLogger(Wget.class);

    private static final String ENCODING_UTF_8 = "UTF-8";

    public static String getPage(String url) {
        if (StringUtil.isBlank(url)) return null;

        HttpClient client = new HttpClient();
        HttpConnectionManagerParams hcmp = client.getHttpConnectionManager().getParams();
        hcmp.setConnectionTimeout(3000);
        
        GetMethod method = new GetMethod(url);
        try {
            int statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + method.getStatusLine());
                return null;
            }
            byte[] responseBody = method.getResponseBody();
            return new String(responseBody, ENCODING_UTF_8);
        } catch (IOException e) {
            logger.error("Failed to download file.", e);
        } finally {
            method.releaseConnection();
        }

        return null;
    }
}
